import {dirname} from "path";
import * as step from '@ali/flow-step-toolkit'
import fs from "fs";
import {IParams} from "./params";
import axios from 'axios';

export const CACHE_TYPE_OSS: string = 'OSS';
export const CACHE_FILE_MAX_SIZE = 2 * 1000 * 1000 * 1000; // 2GB

export async function GetEndpoint(params: IParams): Promise<string> {
    if (!!params.endpoint) {
        return params.endpoint;
    }

    let endpoint = "";
    if (params.cacheType == CACHE_TYPE_OSS) {
        try {
            await axios.get('https://oss-cn-beijing-internal.aliyuncs.com', {timeout: 1000});
            endpoint = 'oss-cn-beijing-internal.aliyuncs.com';
        } catch (error) {
            endpoint = 'oss-accelerate.aliyuncs.com';
        }
    }

    return Promise.resolve(endpoint);
}

export function init(params: IParams): string {
    const parentPath = dirname(params.fileID);
    const fileParentId = params.fileParentID || parentPath;
    params.engineTaskSign = params.engineTaskSign || 'default';

    step.infoV1('PIPELINE_ID=' + params.pipelineID);
    step.infoV1('PIPELINE_NAME=' + params.pipelineName);
    step.infoV1('BUILD_NUMBER=' + params.buildNumber);
    step.infoV1('EMPLOYEE_ID=' + params.operator);
    step.infoV1('WORK_SPACE=' + params.workspace);
    step.infoV1('PROJECT_DIR=' + params.projectDir);
    step.infoV1('PLUGIN_DIR=' + params.pluginDir);
    step.infoV1('BUILD_JOB_ID=' + params.buildJobID);

    const packageDir = `${params.workspace}/packages`;
    fs.rmSync(packageDir, {recursive: true, force: true})
    fs.mkdirSync(packageDir, {recursive: true});

    const artifactFullName = `${packageDir}/${params.cacheName}-${params.engineTaskSign}.tgz`;
    params.fileID = `${fileParentId}/${params.cacheName}-${params.engineTaskSign}.tgz`;

    let archivePath = params.archivePath
    archivePath = archivePath.replace(/\*$/, '');
    step.infoV1(`ARCHIVE_PATH=${archivePath}`);
    archivePath = archivePath.replace(/\$WORK_SPACE/g, params.workspace);
    params.archivePath = archivePath

    step.infoV1(`CACHE_NAME=${params.cacheName}`);
    step.infoV1(`ARCHIVE_PATH=${params.archivePath}`);
    step.infoV1(`COMMAND=${params.command}`);
    step.infoV1(`FILE_ID=${params.fileID}`);
    step.infoV1(`BUCKET_NAME=${params.bucketName}`);
    step.infoV1("");
    step.infoV1("");

    return artifactFullName
}